<script lang="ts" setup>
import type { DataType } from './types';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import { $t } from '@vben/locales';
import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Image,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteLink,
  getLinks,
  postLinksOrders,
  postLinkStatus,
} from '#/api/admin/social';
import Icon from '#/components/Icons';
import { formatImagesList, sortByField, toggleStatus } from '#/utils';

import { FormModalView } from './components';

defineOptions({
  name: 'AdminSocial',
});

const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');

const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isHover: true,
    useKey: true,
    drag: true,
  },
  columnConfig: {
    useKey: true,
  },
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { title: $t('page.common.Code'), type: 'seq', width: 50, dragSort: true },
    { field: 'name', title: $t('page.common.Name') },
    { field: 'url', title: $t('admin.Address') },
    { field: 'status', title: $t('page.common.Status'), slots: { default: 'status' } },
    { field: 'image', title: $t('page.common.Image'), slots: { default: 'image' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getLinks();
        const list = sortByField(data.list, 'list_order');
        data.list = formatImagesList(list);
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const gridEvents: VxeGridListeners<DataType> = {
  async rowDragend() {
    const visibleData = await GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });
    await postLinksOrders({ list_orders: result });
  },
};

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteLink(row);
    $table.remove(row);
    message.success(msg);
  }
};

const onChange = async (row: DataType) => {
  Modal.confirm({
    title: $t('admin.systemMessage'),
    content: $t('admin.confirmTo')+` ${row.status === 0 ? $t('admin.Disable') : $t('admin.Enable')}${row.name}?`,
    async onOk() {
      try {
        await postLinkStatus({
          id: row.id,
          status: row.status,
        });
        message.success(`${row.status === 0 ? $t('admin.Disable') : $t('admin.Enable')}${row.name}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const openDialog = async (title: 'Add' | 'Edit', row?: DataType | null) => {
  formModalApi.setState({
    title: $t('page.common.'+title)+` ${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <Grid :grid-events="gridEvents" :table-title="`${viewTitle} `+$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('Add')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t('page.common.Add')}} {{ viewTitle }}
        </Button>
      </template>
       <template #image="{ row }">
        <Image v-if="row.image " :src="row.image[0]['url']" :height="30" :width="30" />
      </template>
    
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :un-checked-value="0"
          :checked-children="$t('admin.Enable')"
          :un-checked-children="$t('admin.Disable')"
          @change="onChange(row)"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog('Edit', row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            {{$t('page.common.Edit')}}
          </Button>
          <Popconfirm
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{$t('page.common.Delete')}}
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
